package ext.generic.imported.user;

import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.OrganizationServicesHelper;
import wt.org.WTUser;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import ext.com.org.OrgUtil;
import ext.tianma.part.imported.ImportedExcelUtil;

public class ImportedWindchillUser implements RemoteAccess {
	private static final String CLASSNAME = ImportedWindchillUser.class.getName() ;
	
	public static void importedUser( String excelFile ){
		if( excelFile == null ){
			return ;
		}
		
		excelFile = excelFile.trim() ;
		
		if( excelFile.equals("") ){
			return ;
		}
		
		Sheet sheet = ImportedExcelUtil.getFirstSheet(excelFile) ;
		
		if( sheet != null ){
			importedUser( sheet ) ;
		}
	}

	public static void importedUser(Sheet sheet) {
		if( sheet == null ){
			return ;
		}
		
		Iterator<Row> rowIte = sheet.iterator() ;
		
		HashMap<Integer , String> headerMap = new HashMap<Integer , String>() ;
		
		//获取表头
		if( rowIte.hasNext() ){
			Row row = rowIte.next() ;
			headerMap = getHeader( row , headerMap) ;
		}
		
		//遍历Sheet页
		while( rowIte.hasNext() ){
			Row row = rowIte.next() ;
			
			if( row != null ){
				importedUser( row , headerMap ) ;
			}
		}
	}

	private static void importedUser( Row row , HashMap<Integer , String> headerMap ) {
		if( row == null ){
			return ;
		}
		
		HashMap<String,String[]> userAttributesMap = new HashMap<String,String[]>() ;
		
		Iterator<Cell> cellIte = row.iterator() ;
		while( cellIte.hasNext() ){
			Cell cell = cellIte.next() ;
			
			if( cell != null ){
				int columnIndex = cell.getColumnIndex() ;
				String cellHeader = headerMap.get( columnIndex ) ;
				
				String cellValue = ImportedExcelUtil.getCellValueAsString(cell, true) ;
				
				if( cellValue != null && ! cellValue.equals("") ){
					userAttributesMap.put( cellHeader ,  new String[]{cellValue} ) ;
				}
			}
		}
		
		createNewUser( userAttributesMap ) ;
	}
	
	protected static void fixUserAttributesMap(HashMap<String, String[]> userAttributesMap , String userName )
	  {
	    ArrayList localArrayList = new ArrayList();
	    
	    String[] arrayOfString1 = userAttributesMap.get("uid1");
	    String[] arrayOfString2 = userAttributesMap.get("uid2");
	    String[] arrayOfString3 = userAttributesMap.get("uid3");
	    String[] arrayOfString4 = userAttributesMap.get("uid4");
	    
	    localArrayList.add( userName );
	    
	    if ((arrayOfString1 != null) && (arrayOfString1.length > 0)) {
	      localArrayList.add(arrayOfString1[0]);
	    }
	    if ((arrayOfString2 != null) && (arrayOfString2.length > 0)) {
	      localArrayList.add(arrayOfString2[0]);
	    }
	    if ((arrayOfString3 != null) && (arrayOfString3.length > 0)) {
	      localArrayList.add(arrayOfString3[0]);
	    }
	    if ((arrayOfString4 != null) && (arrayOfString4.length > 0)) {
	      localArrayList.add(arrayOfString4[0]);
	    }
	    String[] arrayOfString5 = new String[localArrayList.size()];
	    for (int i = 0; i < localArrayList.size(); ++i) {
	      arrayOfString5[i] = ((String)localArrayList.get(i));
	    }
	    if (localArrayList.size() > 0) {
	    	userAttributesMap.put("uid", arrayOfString5);
	    }
	    userAttributesMap.remove("uid1");
	    userAttributesMap.remove("uid2");
	    userAttributesMap.remove("uid3");
	    userAttributesMap.remove("uid4");
	  }
	
	private static void createNewUser(HashMap<String, String[]> userAttributesMap) {
		if( userAttributesMap == null ){
			return ;
		}
		
		String[] userName = userAttributesMap.get("name") ;
		
		if( userName == null ){
			return ;
		}
		
		if(userName[0] == null ){
			return ;
		}
		
		try {
			WTUser wtuser = OrgUtil.getUserById( userName[0] ) ;
			
			if( wtuser != null ){
				System.out.println("用户已经存在：" + userName[0]);
				
				return ;
			}else{
				System.out.println(">>>> Start Create New User : " + userName[0] ) ;
				
				WTUser newUser = WTUser.newWTUser( userName[0] ) ;
				
				userAttributesMap.remove("name") ;
				
				//PersistenceHelper.manager.store( newUser ) ;
				
				System.out.println(">>>> fixUserAttributesMap ......") ;
				fixUserAttributesMap( userAttributesMap , userName[0] );
				
				System.out.println(">>>> mapAttributes ......") ;
				newUser.mapAttributes( userAttributesMap ) ;
				
				System.out.println(">>>> Start Create Principal ......") ;
				newUser = (WTUser)OrganizationServicesHelper.manager.createPrincipal( newUser );
				System.out.println(">>>> End Create Principal ......") ;
			}
		} catch (WTException e) {
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			e.printStackTrace();
		} 
	}

	/**
	 * 获取Sheet页的表头
	 * 
	 * @param row
	 * @param headerMap
	 * @return
	 */
	private static HashMap<Integer , String> getHeader(Row row, HashMap<Integer, String> headerMap) {
		if( headerMap == null ){
			headerMap = new HashMap<Integer , String>() ;
		}
		
		if( row == null ){
			return headerMap ;
		}
		
		Iterator<Cell> cellIte = row.iterator() ;
		while( cellIte.hasNext() ){
			Cell cell = cellIte.next() ;
			
			if( cell != null ){
				int columnIndex = cell.getColumnIndex() ;
				
				String cellValue = ImportedExcelUtil.getCellValueAsString(cell, true) ;
				
				if( ( cellValue != null ) && ( ! cellValue.equals("") ) ){
					headerMap.put( columnIndex , cellValue ) ;
				}
			}
		}
		
		return headerMap ;
	}
	
	public static void main(String[] args) {
		if( args == null || args.length != 1 ){
			return ;
		}
		
		if( args[0] == null ){
			return ;
		}
		
		if ( ! RemoteMethodServer.ServerFlag ) {
			String method = "importedUser";			
		
			try {
				RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null , new Class[] { String.class }, new Object[] { args[0] });
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}else{
			importedUser( args[0] ) ;
		}
	}
}
